package com.net.xpay.web.controller.merchant;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.net.xpay.web.vo.PayTransBatchVo;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PayMethod;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.AccountLog;
import com.net.xpay.core.domain.PayTransBatch;
import com.net.xpay.core.enums.AccountBillType;
import com.net.xpay.core.enums.PayTransBatchStatus;
import com.net.xpay.core.manager.AccountLogManager;
import com.net.xpay.core.manager.PayTransBatchManager;
import com.net.xpay.core.model.PayTransBatchSearchModel;
import com.net.xpay.core.service.PayTransBatchService;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2020/5/7 13:31

 */
@RestController
@Slf4j
@RequestMapping("/merchant/pay-trans-batch")
@Api(tags = "商户/手工打款", description = "商户 手工打款 net")
public class PayTransBatchController {

    @Autowired
    private PayTransBatchService payTransBatchService;

    @Autowired
    private PayTransBatchManager payTransBatchManager;

    @Autowired
    private AccountLogManager accountLogManager;


    /**
     * 确认打款
     * @param payMethod 0 pc 1 移动二维码 2 移动链接
     */
    @ApiOperation("确认打款")
    @PostMapping("/confirm")
    public ResultData<String> confirmPayTransBatch(@ApiIgnore @RequestUser User merchant, HttpServletResponse response, Long id, Integer payMethod) {
        PayTransBatch payTransBatch = payTransBatchService.batchPayTrans(merchant, id, null, null, null, payMethod);
        if (payMethod != null && payMethod.equals(PayMethod.MOBILE_QR_CODE)) {
            return new ResultData<>(payTransBatch.getMobilePayQrCode());
        }
        return new ResultData<>(payTransBatch.getLastPayUrl());
    }

    /**
     * 关闭批次
     */
    @ApiOperation("关闭批次")
    @PostMapping("/close")
    public ResultData<PayTransBatchVo> closePayTransBatch(@ApiIgnore @RequestUser User merchant, HttpServletResponse response, Long id) {
        PayTransBatch payTransBatch = payTransBatchService.closePayTransBatch(merchant, id);
        PayTransBatchVo vo = new PayTransBatchVo();
        BeanCopierUtil.copy(payTransBatch, vo);
        return new ResultData<>(vo);
    }

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<PayTransBatchVo> searchPayTransBatch(@ApiIgnore @RequestUser User merchant, @RequestBody PayTransBatchSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());

        List<PayTransBatch> payTransBatchList = payTransBatchManager.search(searchModel);
        List<PayTransBatchVo> vos = BeanCopierUtil.batchCopy(PayTransBatch.class, PayTransBatchVo.class, payTransBatchList);

        for (PayTransBatchVo vo : vos) {
            if (Lists.newArrayList(PayTransBatchStatus.DISUSE, PayTransBatchStatus.INVALID, PayTransBatchStatus.FAIL, PayTransBatchStatus.PART_SUCCESS).contains(vo.getStatus())
                    && vo.getServicePrice() != null && vo.getServicePrice() != 0L)  {
                AccountLog accountLog = accountLogManager.findByRelatedId(merchant.getId(), AccountBillType.PAY_TRANS_SERVICE_PRICE_REFUND, vo.getLastSummaryId());
                if (accountLog == null) {
                    continue;
                }
                vo.setRefund(accountLog.getChange());
                vo.setRefundId(accountLog.getId());
            }
        }

        long count = payTransBatchManager.searchCount(searchModel);

        return new ResultPagedList<>(vos, count, searchModel);
    }

    /**
     * 打款批次导出
     */
    @ApiOperation("打款批次导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportPayTransBatch(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        PayTransBatchSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, PayTransBatchSearchModel.class);
        searchModel.setUserId(merchant.getId());
        long count = payTransBatchManager.searchCount(searchModel);
        if (count > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出数据超过10000条，无法导出");
        }
        List<PayTransBatch> records = payTransBatchManager.list(searchModel);
        if (records.size() > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出数据超过10000条，无法导出");
        }
        for (PayTransBatch batch : records) {
            if (batch.getRefund() != null && batch.getRefund() > 0L) {
                continue;
            }
            if (Lists.newArrayList(PayTransBatchStatus.DISUSE, PayTransBatchStatus.INVALID, PayTransBatchStatus.FAIL, PayTransBatchStatus.PART_SUCCESS).contains(batch.getStatus())
                    && batch.getServicePrice() != null && batch.getServicePrice() != 0L)  {
                AccountLog accountLog = accountLogManager.findByRelatedId(merchant.getId(), AccountBillType.PAY_TRANS_SERVICE_PRICE_REFUND, batch.getLastSummaryId());
                if (accountLog == null) {
                    batch.setRefund(0L);
                } else {
                    batch.setRefund(accountLog.getChange());
                }

            }
        }

        Map<String, Object> model = new HashMap<>();
        model.put("records", records);

        String fileName = "转账记录.xlsx";
        String template = "/excel/tpl/转账记录.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }

        return new ResultData<>();
    }


}
